<?php
/**
 * 商城首页
 * Created by atom.
 * User:xuanfeng
 * Date: 2020/2/27
 * Time: 13:07:45
 */

namespace app\home\controller;


use app\common\model\Goods;
use app\common\model\Jhsms;
use app\common\model\User;
use think\Exception;
use think\Session;

class Index extends Common
{

    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 商城首页
     */
    public function index()
    {
        //首页是否显示通知
        $show_flag = session("show_flag");

        $this->templateTitle("首页");
        //查看是否有首页通知信息
        $info = db("index_notice")->find();
        $show_info = 0;
        if ($info) {
            if ($show_flag < time()-3*60*10) {
                if ($info["is_show"] == 1) {
                    $show_info = 1;
                }
                session("show_flag", time());
            }
        }
        $this->assign("info", $info);
        $this->assign("show_info", $show_info);
        //首页轮播新闻
        $newlist = db("news")->where("status", 1)->order("display_order desc,create_time desc")->limit(5)->select();
        $this->assign("newlist", $newlist);
        //页面加载延时
        $load_time = config("setting.load_time") ? config("setting.load_time") : 1;
        $this->assign("load_time", $load_time);
        $goods_list = Goods::getGoodsList();
        //查询今日已预约商品
        $apply_id = db("apply")->where("nowdate", date("Ymd"))->where("uid", session("user_id"))->column("proid");
        $this->assign("apply_id", $apply_id);
        $date_time = strtotime(date("Y-m-d"));
        $now_time = now_datetime();
        $return_id = 0;
        $return_time = 0;
        $slide = 0;
        foreach ($goods_list as $k=>&$item) {
            $item["start_time"] = $date_time + $item["time_start"];
            $item["end_time"] = $date_time + $item["time_end"];
            $item['can_sale'] = 1;
            if ($item['isclose'] == 2) {
                $item['can_sale'] = 2;
            } else {
                //商品是否已经超时 0 未超时 1 已经超过预约时间但是还处在开奖期间  2 已经过期
                $item["over_status"] = 0;
                if ($item["start_time"] <= $now_time && $item['end_time'] >= $now_time) {
                    //今日商品处在开奖时间段内
                    $item["over_status"] = 1;
                    $item['over_text'] = '匹配中';
                } elseif ($item['start_time'] > $now_time) {
                    //商品还未开始开奖
                    if (empty($return_id) && !in_array($item['id'], $apply_id)) {
                        //统计即将开奖的商品
                        $return_id = $item['id'];
                        $return_time = $item['start_time'];
                    } else {
                        if ($item['start_time'] < $return_time && !in_array($item['id'], $apply_id)) {
                            //该商品比已经记录的商品开奖时间更早，所以此处替换一下即将开奖的商品
                            $return_id = $item['id'];
                            $return_time = $item['start_time'];
                            $slide = $k;
                        }
                    }
                    //用户是否已经预约过
                    if (in_array($item['id'], $apply_id)) {
                        //预约过
                        $item['over_status'] = 3;
                        $item['over_text'] = '待匹配';
                    } else {
                        $item['over_status'] = 0;
                        $item['over_text'] = '预约';
                    }
                } elseif ($item['end_time'] < $now_time) {
                    //商品已经过期
                    $item['over_status'] = 2;
                    $item['over_text'] = '预约结束';
                }
            }
        }
        $this->assign("return_id", $return_id);
        $this->assign("slider", $slide);
        $this->assign("return_time", $return_time);
        $this->assign("goods_list", $goods_list);
        return $this->fetch("index");
    }

    /**
     * 预约/购买订单
     */
    public function buyOrder()
    {
        set_time_limit(0);
        $pro_id = input("id");
        $user_id = session("user_id");
        if (empty($user_id)) {
            $this->ajaxError("请先登录！");
            exit;
        }
        try {
            //校验用户信息
            $userinfo = \app\common\model\User::verifyUser($user_id);
            //校验商品信息
            $good = Goods::checkGoods($pro_id, $user_id);
            //根据商品状态判断是预约还是购买
            if (($good["time_start"] + strtotime(date("Ymd"))) >= time()) {
                //预约商品
                $this->doapply($userinfo, $good);
                exit;
            } else {
                $this->ajaxError('已过预约时间，请下次再来');
            }
        } catch (\Exception $e) {
            $this->ajaxError($e->getMessage());
        }
    }

    /*执行预约---xuanfeng---20190622*/
    private function doapply($userinfo, $product_con)
    {
        //获取当前ip xuanfeng 2020-07-31
        $ipstr = get_client_ip();

        $map['uid'] = $userinfo['id'];
        $map['proid'] = $product_con['id'];
        $map['nowdate'] = date('Ymd');
        $map['status'] = 1;
        //先看一下用户的共享豆是否充足，不足就不让预约
        $map['delpoint'] = $product_con['point_start'];
        if ($userinfo['integral'] < $map['delpoint']) {
            $this->ajaxError("共享豆不足，预约失败");
        }
        $map['ctime'] = time();
        $today_timestamp = date('Y-m-d');
        $map['returntime'] = ($product_con['time_start'] + strtotime($today_timestamp));
        $map['status'] = 0;
        $map['isadd'] = 2;
        $map['proid'] = $product_con['id'];
        $map['title'] = '[预约]' . $product_con['title'];
        $map['rank'] = rand(1000, 9999);
        $map['ipstr'] = $ipstr;
        $s2 = db('apply')->insert($map);
        if ($s2) {
            //减去会员共享豆，并新增共享豆记录
            db('user')->where('id="' . trim($userinfo['id']) . '"')->setDec("integral", $product_con["point_start"]);
            points_his($userinfo['id'], 2, $map['delpoint'], 0, '预约[' . $product_con['title'] . ']扣除');
            $this->ajaxSuccess("商品预约成功", ["type" => 1]);
        } else {
            $this->ajaxError("商品预约失败");
        }
    }

    /*执行购买---xuanfeng ---20190623*/
    private function dobuy($userinfo, $product_con)
    {

        $f = fopen("lock.lock", "w+");
        if (flock($f, LOCK_EX)) {
            //校验今天是否已经购买过此商品
            $now_date = strtotime(date("Ymd"));
            $order = db(config("db_order_table"))->where("buyuid='" . $userinfo['id'] . "' and productid='" . $product_con['id'] . "' and thatdatetime='" . $now_date . "'")->find();
            if (!empty($order)) {
                throw new Exception("此商品每天只能抢购一次！");
            }

            //查一下预约是否有，如果买单失败就把共享豆退回去
            //判断有用户是否还存在
            $is_exist = db('user')->where('id', $userinfo['id'])->find();
            if (empty($is_exist)) {
                $this->ajaxError("订单异常，请重新购买");
            }
            $data_apply['uid'] = $userinfo['id'];
            $data_apply['proid'] = $product_con['id'];
            $data_apply['nowdate'] = date('Ymd');
            $data_apply['status'] = 0;
            $s = db('apply')->where($data_apply)->find();


            $price_start = $product_con['price1'];
            $price_end = $product_con['price2'];
            //查一下可配对的单子有多少，但是不能包含自己买的单子
            $order_have_map = "basicprice>'" . $price_start . "' and basicprice<='" . $price_end . "' and peiduistatus=1 and xs=2 and buyuid<>'" . $userinfo['id'] . "'";
            $order_have_map = $order_have_map . " and cansaletime<='" . time() . "' ";
            //如果已经有预约，那就必须查一下这个人有没有被指定订单
            if (!empty($s)) {
                $focus_applyid = $s['id'];
                $order_have_s = $order_have_map . " and applyid='" . $focus_applyid . "' ";
                $order_have = db(config('db_order_table'))->where($order_have_s)->order('id asc')->value('id');
            }
            if (empty($order_have)) {
                $order_have_map = $order_have_map . " and applyid='0' ";
                $order_have = db(config('db_order_table'))->where($order_have_map)->order('id asc')->value('id');
            }
            //  echo db()->getlastsql();exit;
            //不可描述
            if ($userinfo['hello'] == 2) {
                $order_have = '';
            }

            //没有匹配的订单，直接返回给客户，告诉客户额度没了
            if (empty($order_have)) {
                /*先把预约的共享豆退回去，再把这个预约状态改成退还*/
                if (!empty($s)) {
                    /*新增预约失败，并退还*/
                    $newdata = $s;
                    $newdata['status'] = 2;
                    db('apply')->where("id='" . $s['id'] . "'")->update($newdata);//先把原来预约取消
                    $newdata['title'] = $s['title'] . '-共享豆退还';
                    unset($newdata['id']);
                    $newdata['isadd'] = 1;
                    $newdata['ctime'] = time();
                    db('apply')->insert($newdata);//再把预约失败还回去
                    //先把会员的共享豆加回去
                    db('user')->where("id='" . $userinfo['id'] . "'")->setInc('integral', $s['delpoint']);
                    //再把会员的共享豆历史加上
                    points_his($userinfo['id'], 1, $s['delpoint'], 0, $s['title'] . '-预约失败退还');
                }
                if ($userinfo['is_our'] == 1) {
                    $this->ajaxError("抢购失败!!");/*非官方号*/
                }
            } else {
                /*如果有符合条件的订单并且客户购买，判断一下用户是否预约，把预约的扣除共享豆确定下来*/
                if (!empty($s)) {
                    //确定共享豆扣除，不返还
                    $newdata['status'] = 1;
                    db('apply')->where("id='" . $s['id'] . "'")->update($newdata);//先把原来预约取消
                }
            }

            //判断是否预约
            if (empty($s)) {
                //检查一下会员你的共享豆够不够，不够就不让买
                if ($product_con['point_end'] > $userinfo['integral']) {
//                if($userinfo['is_our'] == 1){ /*判断是否非官方号*/
                    $this->ajaxError("抱歉，共享豆不够购买此商品");
//                }
                }
                //先把会员共享豆扣了，然后添加新的订单
                db('user')->where("id='" . $userinfo['id'] . "'")->setDec('integral', $product_con['point_end']);
                //再把会员的共享豆历史加上
                points_his($userinfo['id'], 2, $product_con['point_end'], 0, '购买[' . $product_con['title'] . ']扣除');
                //没预约扣除多少共享豆
                $data_sure['caifen'] = $product_con['point_end'];
            } else {
                //已预约扣除多少共享豆
                $data_sure['caifen'] = $product_con['point_start'];
            }

            /*如果是空订单并且是管理员，直接购买，无需配对*/
            if (empty($order_have) && $userinfo['is_our'] == 2) {
                $data_sure['price'] = rand($product_con['price1'], $product_con['price2']);
            } else {
                //下单并绑定uid,然后获取这条订单的所有信息，价格交给下个新订单，并生成收益列表
                $bind_order['peiduiuid'] = $userinfo['id'];
                $bind_order['peiduistatus'] = 2;
                $bind_order['peiduitime'] = time();
                $bind_order["match_pro_id"] = $product_con["id"];
                $bind_order["match_pro_title"] = $product_con["title"];
                //获取订单所有信息
                $that_order_one = db(config('db_order_table'))->where("id='" . $order_have . "'")->find();
                $data_sure['price'] = $that_order_one['basicprice'];
                $data_sure['peiduiid'] = $that_order_one['id'];
                if (true) {
                    //配对完成给双方发短信,暂未处理是否开启
                    //买家收短信 $userinfo['selfphone'];
                    if (config("setting.smsmy_on") == 1) {
                        //短信通道未关闭！！
                        $jh_sms = new Jhsms();
                        $jh_sms->send_order_tips($userinfo['selfphone']);
                        $phone_buy = db("user")->where("id", $that_order_one['buyuid'])->value("selfphone");
                        $jh_sms->send_order_tips($phone_buy);
                    }
                }

            }
            // 然后再新增一个order数据
            if ($userinfo['is_our'] == 2) {
                $data_sure['xs'] = 2;
            }
            $data_sure['buyuid'] = $userinfo['id'];
            $data_sure['productid'] = $product_con['id'];
            $data_sure['title'] = $product_con['title'];
            $data_sure['daynum'] = $product_con['daynum'];
            $data_sure['earnpercent'] = $product_con['daypercent'];
            //一共能赚多少钱，本金加赚的钱有多少
            $countprofit = countprofit($data_sure['price'], $data_sure['daynum'], $data_sure['earnpercent']);
            $data_sure['buyuidatc'] = $product_con['atcnum'];

            $data_sure['dayaddprice'] = $countprofit['profitall'];
            $data_sure['basicprice'] = $countprofit['profit_and_day'];
            $data_sure['ctime'] = time();
            $data_sure['peiduistatus'] = 1;
            $data_sure['peiduiuid'] = 0;
            $data_sure['paystatus'] = 0;
            $data_sure['paytime'] = 0;
            $data_sure['payimg'] = '';

            $cansaletime = ($data_sure['ctime'] + 86400 * $product_con['daynum']);
            $cansaletimedate = date('Y-m-d', $cansaletime);
            $data_sure['cansaletime'] = strtotime($cansaletimedate);
            $now_day_dates = date('Y-m-d');
            $data_sure['thatdatetime'] = strtotime($now_day_dates);
//        $data_sure['ordersn'] = coid($data_sure['buyuid']);
            //先新增order表，再新增利润表
            $order_new_id = db(config('db_order_table'))->insertGetId($data_sure);
            $bind_order["match_oid"] = $order_new_id;
            db(config('db_order_table'))->where("id='" . $order_have . "'")->update($bind_order);
            for ($i = 1; $i <= $product_con['daynum']; $i++) {
                $data_detail['orderid'] = $order_new_id;
                $data_detail['uid'] = $userinfo['id'];
                $data_detail['earnmoney'] = $countprofit['profitday'];
                $detail_time = ($data_sure['thatdatetime'] + 86400 * $i);
                $data_detail['dotime'] = date('Ymd', $detail_time);
                $data_detail['status'] = 1;
                $data_detail['ctime'] = time();
                db('orderearn')->insert($data_detail);
            }
        }
        fclose($f);

        $this->ajaxSuccess("购买成功");
    }


    /**
     * 会员登录
     */
    public function login()
    {
        $this->templateTitle("会员登录");
        if (request()->isAjax()) {
            $data = input("post.");


            try {
                $res = \app\common\model\User::login($data["selfphone"], $data["passwd"]);
                session("user_id", $res["uid"]);
                session("show_flag", 2);
                $this->ajaxSuccess("登录成功");
            } catch (\Exception $e) {
                $this->ajaxError($e->getMessage());
            }


            //校验验证码
            if (!captcha_check($data["code"])) {
                $this->ajaxError("验证码错误");
            } else {
                //代码移动到上面去！
            }
        }
        return $this->fetch("login");
    }

    /**
     * 会员注册
     */
    public function register()
    {
        $this->templateTitle("免费注册");
        if (request()->isAjax()) {
            $data = input("post.");
            try {
                if ($data['vcode'] == config("setting.smsnewcode")) {
                    //如果输入的验证码和后台的一致，不验证验证码了。
                } else {
                    //校验验证码
                    Jhsms::verifyCaptcha($data["selfphone"], $data['vcode'], 1);
                }
                //检查用户名是否为纯数字！ xuanfeng 2020-07-31
                $num_user = intval($data["username"]);
                if ((string)$num_user === (string)$data["username"]) {
                    $this->ajaxError("用户名不能是纯数字！！");
                }

                //校验二级密码
                if ($data["sepasswd"] != $data["confirm_sepasswd"]) {
                    $this->ajaxError("两次二级密码输入不同");
                }
                \app\common\model\User::register(remove_tag($data["username"]), $data["selfphone"], $data["passwd"], $data["confirm_passwd"], $data["sepasswd"], $data["invite_code"]);
                $this->ajaxSuccess("注册成功");
            } catch (\Exception $e) {
                $this->ajaxError($e->getMessage());
            }
        }
        //如果是扫码进入注册 默认代入邀请手机号
        $code = input('codes', '');
        $this->assign('code', base64_decode($code));
        return $this->fetch("register");
    }

    /**
     * 忘记密码
     */
    public function forget()
    {
        $this->templateTitle("忘记密码");
        return $this->fetch("forget");
    }

    /*
     * 忘记密码 ajax
     * */
    public function doforget()
    {
        $tel = trim($_POST['phone']);
        $codes = trim($_POST['codes']);
        $pwd = trim($_POST['pwds']);
        $data['passwd'] = md5(md5($pwd));
        if (!User::exists($tel)) {
            $this->ajaxError('该手机号还未注册，请先注册');
        }
        $upass = db('user')->where("selfphone='" . $tel . "'")->field('passwd')->find();
        if (!empty($upass) && $upass['passwd'] == $data['passwd']) {
            $this->ajaxError('新密码和原密码一致，无需修改');
        }
        try {
            Jhsms::verifyCaptcha($tel, $codes, 2);
            $s = db('user')->where("selfphone='" . $tel . "'")->update($data);
            if ($s) {
                $this->ajaxSuccess("找回成功");
            } else {
                $this->ajaxError('找回失败');
            }
        } catch (\Exception $e) {
            $this->ajaxError($e->getMessage());
        }
    }

    /**
     * 获取手机验证码
     */
    public function getVcode()
    {
        $telephone = input("telephone");
        $type = input("type");
        if (verify_mobile($telephone)) {
            try {
                $sms = new Jhsms();
                $sms->send_sms($telephone, $type);
                $this->ajaxSuccess("发送成功，请注意查收");
            } catch (\Exception $e) {
                $this->ajaxError($e->getMessage());
            }
        } else {
            $this->ajaxError("手机号格式错误");
        }
    }

    /**
     * 用户协议及隐私政策
     */
    public function treaty()
    {
        $this->templateTitle("用户协议及隐私政策");
        $info = db("service")->where("type", 3)->find();
        $this->assign("info", $info);
        return $this->fetch("treaty");
    }

    /**
     * 退出登录
     */
    public function signout()
    {
        header("Content-Type:text/html; charset=utf-8");
        session('user_id', null);
        session("show_flag", null);
        return $this->fetch("login");
    }

    /**
     * 矿机 2020-08-03 23:16 xuanfeng
     * 读取所有可以兑换的矿机
     */
    public function ourshop()
    {
        $this->templateTitle("商城");

        $model = db("shop_goods");
        $list = $model->where("isshow=1")->order("sort desc,id asc")->paginate(20);
        $this->assign("list", $list);
        return $this->fetch("ourshop");
    }


    /**
     * 矿机 2020-08-03 23:23 xuanfeng
     * 读取我当前拥有的矿机，不过是还没有过期的，过期后状态一定要改为:2
     */
    public function myshop()
    {
        $this->templateTitle("我的矿机");
        $user_id = session("user_id");
        $model = db("shopmy");
        $list = $model->where("uid='" . $user_id . "' and daynum>usedaynum")->order("id desc")->paginate(5);
        $list = $list->all();
        $this->assign("list", $list);
        return $this->fetch("myshop");
    }

    /**
     * 矿机ajax无限加载 2020-08-04 13:55 xuanfeng
     */
    public function ajaxmyshop()
    {
        $user_id = session("user_id");

        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 2;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;

        $model = db("shopmy");
        $list = $model->where("uid='" . $user_id . "' and daynum>usedaynum")->order("id desc")->paginate(5);
        $ary = [];
        if (!empty($list)) {
            $ary = $list->all();
            foreach ($ary as $k => $v) {
                $ary[$k]['buytime'] = date('Y-m-d H:i:s', $v['buytime']);
                $ary[$k]['gitbot'] = ($v['daynum'] * $v['dayearn']);
            }
        }
        echo json_encode($ary);
    }


    /**
     * 矿机 2020-08-03 23:59 xuanfeng
     * 读取我当前拥有的,但是已经过期的矿机
     */
    public function endshop()
    {
        $this->templateTitle("过期矿机");
        $user_id = session("user_id");
        $model = db("shopmy");
        $list = $model->where("uid='" . $user_id . "' and daynum=usedaynum")->order("id desc")->paginate(5);
        $list = $list->all();
        $this->assign("list", $list);
        return $this->fetch("endshop");
    }

    /**
     * 过期矿机ajax无限加载 2020-08-04 13:55 xuanfeng
     */
    public function ajaxendshop()
    {
        $user_id = session("user_id");
        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 2;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;

        $model = db("shopmy");
        $list = $model->where("uid='" . $user_id . "' and daynum=usedaynum")->order("id desc")->paginate(5);
        $ary = [];
        if (!empty($list)) {
            $ary = $list->all();
            foreach ($ary as $k => $v) {
                $ary[$k]['buytime'] = date('Y-m-d H:i:s', $v['buytime']);
                $ary[$k]['gitbot'] = ($v['daynum'] * $v['dayearn']);
            }
        }
        echo json_encode($ary);
    }


}
